package com.compass.service;

import com.compass.constant.Admin;
import com.compass.entity.User;
import com.compass.mapper.UserMapper;
import com.compass.vo.LoginUser;
import com.compass.vo.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: li
 * Date: 2019/3/10
 * Time: 16:49
 * PROJECT：compass
 * PACKAGE: com.compass
 *
 * @author:55324936@qq.com To change this template use File | Settings | File Templates.
 */
@Service
@Slf4j
public class UserService {

    @Autowired
    UserMapper userMapper;
    /**
     * 登录校验用户是否存在
     * @param user
     * @return
     * **/
    public ResponseMessage checkUser(User user){
        User user1 = userMapper.checkUser(user);
        //简单的做
        if(null ==user1){
            return ResponseMessage.errorResponse("用户不存在或者密码错误");
        }
        LoginUser loginUser=new LoginUser();
        //第1个参数是被拷贝的对象,第2个参数是目标拷贝的对象
        BeanUtils.copyProperties(user1,loginUser);
        return ResponseMessage.successResponse(loginUser);
    }
    /**
     * 注册用户
     * @param user
     * @return
     * **/
    public ResponseMessage register(User user){
        try {
            int i = userMapper.register(user);
            if(i==1){
                return ResponseMessage.successResponse();
            }else {
                return ResponseMessage.errorResponse("注册异常,请联系管理员");
            }
        }catch (DuplicateKeyException duplicateKeyException){
            duplicateKeyException.printStackTrace();
            return ResponseMessage.errorResponse("已经存在的用户名");
        } catch (Exception e){
            e.printStackTrace();
            return ResponseMessage.errorResponse("注册异常,请联系管理员");
        }
    }
    /**
     * 获取用户列表为新增项目成员使用
     * **/
    public ResponseMessage userList(){
        List<User> userList= userMapper.userList();
        List<Map> mapList =new ArrayList<>();
        try {
            userList.forEach(user -> {
                //id text  {"id":123,"text":"xxx"}
                Map map = new HashMap();
                map.put("id", user.getId());
                map.put("text", user.getUserName());
                mapList.add(map);
            });
            return ResponseMessage.successResponse(mapList);
        }catch (Exception e){
           log.error("获取用户列表异常",e);
           return ResponseMessage.errorResponse("获取用户列表异常,"+Admin.ADMIN_MESSAGE);
        }
    }
}
